import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import api from '../../api';
import { getKey } from '../../../utils/reactComponentInfoUtils.js';
import urls from '../../urls';

export const fetchComponents = createAsyncThunk(
  'componentInfos/fetchComponents',
  async (_, { rejectWithValue }) => {
    try {
      const { data: comps } = await api.get(urls.COMPONENTS);
      return comps.map(comp => ({
        name: comp.name,
        absolutePath: comp.absolutePath,
        jsDoc: comp.jsDoc,
        key: getKey(comp.name, comp.absolutePath),
      }));
    } catch (err) {
      return rejectWithValue(err);
    }
  }
);

const componentInfosSlice = createSlice({
  name: 'componentInfos',
  initialState: {
    components: [],
    loading: false,
    error: null
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchComponents.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchComponents.fulfilled, (state, action) => {
        state.loading = false;
        state.components = action.payload;
      })
      .addCase(fetchComponents.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      });
  }
});

export default componentInfosSlice.reducer;